package com.tanhua.dubbo.server.api;

import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.enums.CommentType;
import com.tanhua.dubbo.server.pojo.Comment;
import com.tanhua.dubbo.server.vo.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service(version = "1.0.0")
@Slf4j

public class QueryAllCommentsApiIml implements QueryAllCommentsApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 查询"评论"列表
     *
     * @param page
     * @param pageSize
     * @param sortProp  排序字段
     * @param sortOrder ascending 升序 descending 降序
     * @param publishId
     * @return
     */
    @Override
    public PageInfo<Comment> queryCommentList(Integer page, Integer pageSize, String sortProp, String sortOrder, String publishId) {

        PageRequest pageRequest = null;
        //先将评论进行分页处理
        if ("ascending".equals(sortOrder)){
             pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.asc(sortProp)));
        }else if ("descending".equals(sortOrder)){
             pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc(sortProp)));
        }else {
            log.error("排序参数有误");
            //1.排序参数有误
            return null;
        }

        Query query = new Query(Criteria
                .where("publishId").is(new ObjectId(publishId))
                .and("commentType").is(CommentType.COMMENT.getType())).with(pageRequest);
        List<Comment> comments = mongoTemplate.find(query, Comment.class);
        PageInfo<Comment> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        /*if(CollUtil.isEmpty(comments)){
            return pageInfo;
        }*/
        pageInfo.setRecords(comments);
        return pageInfo;
    }
}
